layui.sort = function(data, key, sorters) {
    /** @type {*} */
    var obj = JSON.parse(JSON.stringify(data || []));
    return key ? (obj.sort(function($cookies, matrix) {
        /** @type {RegExp} */
        var QUnit = /^-?\d+$/;
        var a = $cookies[key];
        var b = matrix[key];
        return QUnit.test(a) && (a = parseFloat(a)), QUnit.test(b) && (b = parseFloat(b)), /*a && !b ? 1 : !a && b ? -1 : a > b ? 1 : a < b ? -1 : 0*/ a-b;
    }), sorters && obj.reverse(), obj) : obj;
};

layui.config({
    base: 'js/' //设定扩展的Layui组件的所在目录，一般用于外部组件扩展
}).extend({
    'form2':'form2'
});

layui.use(['form2','laydate','layer','table'],function () {
    $.home = function () {
        return{
            data:'',
            classId:'',
            init:function () {
                this.initSelect();
                this.eventListen();
            },
            tableData:'',
            initSelect:function(){
                this.ajaxRequest('/stats_brush/stuBrashInit','get',null,false,function (res) {
                    $.home.data = res;

                    layui.laydate.render({
                        elem: '.test-item',
                        range: '~',
                        value: res.startTime + ' ~ ' + res.endTime
                    });

                    $.home.renderSelect(res.subject,'subjectId',function () {

                    });
                    $.home.renderSelect(res.schoolIds,'schoolIds',function () {
                        $.home.serchClass();
                    });
                    $.home.renderSelect(res.subTypeArr,'subTypeArr',function () {
                        $.home.searchBook();
                    });
                    layui.form2.render();
                });
            },
            searchBook:function(){
                $.home.ajaxRequest('/stats_brush/getBook','post',{
                    subjectId:$('#subjectId').val(),
                    subType:$('#subTypeArr').val()
                },false,function (res) {
                    $.home.renderSelect(res,'bookId');
                });
            },
            serchClass:function(){
                $.home.ajaxRequest('/stats_brush/getClass','post',{schoolIds:$('#schoolIds').val()},false,function (res) {
                    $.home.classId = res;
                    $('#classId option').remove();
                    $.home.renderSelect(res,'classId');
                });
            },
            renderSelect:function (data,elem,callback) {
                var template = '';
                var index = 0;
                switch (elem){
                    case 'schoolIds':
                        $.each(data,function (k,v) {
                            template += '<option value="'+ k +'" '+ ( index === 0 ? "selected":"" ) +'>'+ v +'</option>';
                            index++;
                        });
                        break;
                    case 'subjectId':
                        $.each(data,function (i,item) {
                            template += '<option value="'+ item.subjectId +'" '+ ( i === 0 ? "selected":"" ) +'>'+ item.subjectName +'</option>';
                        });
                        break;
                    case 'subTypeArr':
                        $.each(data,function (k,v) {
                            template += '<option value="'+ k +'" '+ ( k === 1 ? "selected":"" ) +'>'+ v +'</option>';
                        });
                        break;
                    case 'bookId':
                        template = '<option value="">请选择书本</option>';
                        $.each(data,function (i,item) {
                            template +='<option value="'+ item.bookid +'">'+ item.bookname +'</option>'
                        });
                        break;
                    case 'classId':
                        template = '<option value="">请选择班级</option>';
                        $.each(data,function (k,v) {
                            template += '<option value="'+ k +'">'+ v +'</option>';
                        });
                        break;
                }
                $('#'+elem).html(template);
                callback&&callback()
            },
            eventListen:function () {
                var bool = true;
                $('.submit span').click(function () { //搜索
                    var index = $(this).index();
                    var timeValue = $('[name="time"]').val().split('~');
                    var classId = $('#classId').val();
                    var subject = $("#subjectId").val();
                    var subtype = null;
                    $.each($.home.data.subject,function (i,item) {
                        if(item.subjectId == subject){
                            subtype = item.subType;
                        }
                    });
                    switch (index){
                        case 0:
                            if(!bool){
                                layui.layer.msg('请不要频繁搜索',{icon:2});
                                return;
                            }
                            bool = false;
                            var data = {
                                startTime:$.trim(timeValue[0]),
                                endTime:$.trim(timeValue[1]),
                                schoolId:$('#schoolIds').val(),
                                bookId:$('#bookId').val().join(','),
                                classId:classId
                            };
                            if(!data.bookId){
                                layui.layer.msg('请先选择书本',{icon:2});
                                bool = true;
                                return;
                            }
                            $('.loading').show();
                            $.home.ajaxRequest('/stats_brush/getStuBrush','post',data,true,function (res) {
                                $.home.tableData = res;
                                $('.loading').hide();
                                layui.table.render({
                                    elem: '#questionTable',
                                    data:res,
                                    height:'full-80',
                                    cols: [[
                                        {field:'id', width:60 ,type:'numbers',title:'ID'},
                                        {field:'className',width:80, title:'班级'},
                                        {field:'userName', width:100, title:'姓名'},
                                        {field:'hp', width:80, sort: true,title:'体力',align:'right'},
                                        {field:'credit', width:90, sort: true,title:'诚信分',align:'right'},
                                        {field:'countScore', width:120, sort: true,title:'历史总积分',align:'right'},
                                        {field:'integral', width:80, sort: true,title:'局得分',align:'right'},
                                        {field:'homeWorkNum', width:155, sort: true,title:'作业完成数（局）',align:'right'},
                                        {field:'selfWorkNum', width:140, sort: true,title:'自练情况（局）',align:'right'},
                                        topicOld(subtype),
                                        {field:'topicNum', width:90, sort: true,title:'出结果题量',align:'right'},
                                        {field:'rightCount', width:110, sort: true,title: type(subtype),align:'right'},
                                        {field:'rightRate', width:110,sort: true,title:'正确率(%)',align:'right'},
                                        {field:'timeCost', width:150,sort: true,title:'平均做题时间(秒)',align:'right'}
                                    ]],
                                    limit:res.length
                                });
                            });
                            setTimeout(function () {
                                bool = true;
                            },3000);
                            break;
                        case 1:
                            if(!$('#bookId').val().join(',')){
                                layui.layer.msg('请先选择书本',{icon:2});
                                return
                            }
                            data = {
                                startTime:$.trim(timeValue[0]),
                                endTime:$.trim(timeValue[1]),
                                schoolId:$('#schoolIds').val(),
                                bookId:$('#bookId').val().join(','),
                                classId:classId
                            };
                            window.open('/stats_brush/exportStuExcel?' +
                                'schoolId='+$('#schoolIds').val()+
                                '&startTime='+ timeValue[0] +
                                '&endTime='+timeValue[1]+
                                '&bookId='+$('#bookId').val().join(',')+
                                '&classId='+classId.join(',')+
                                '&subType='+subtype);
                            $.home.ajaxRequest('/stats_brush/getStuBrush','post',data,true,function (res) {
                                $.home.tableData = res;
                                $('.loading').hide();
                                layui.table.render({
                                    elem: '#questionTable',
                                    data:res,
                                    height:'full-80',
                                    cols: [[
                                        {field:'id', width:60 ,type:'numbers',title:'ID'},
                                        {field:'className',width:80, title:'班级'},
                                        {field:'userName', width:100, title:'姓名'},
                                        {field:'hp', width:80, sort: true,title:'体力',align:'right'},
                                        {field:'credit', width:90, sort: true,title:'诚信分',align:'right'},
                                        {field:'countScore', width:120, sort: true,title:'历史总积分',align:'right'},
                                        {field:'integral', width:80, sort: true,title:'局得分',align:'right'},
                                        {field:'homeWorkNum', width:155, sort: true,title:'作业完成数（局）',align:'right'},
                                        {field:'selfWorkNum', width:140, sort: true,title:'自练情况（局）',align:'right'},
                                        topicOld(subtype),
                                        {field:'topicNum', width:90, sort: true,title:'出结果题量',align:'right'},
                                        {field:'rightCount', width:110, sort: true,title: type(subtype),align:'right'},
                                        {field:'rightRate', width:110,sort: true,title:'正确率(%)',align:'right'},
                                        {field:'timeCost', width:150,sort: true,title:'平均做题时间(秒)',align:'right'}
                                    ]],
                                    limit:res.length
                                });
                            });
                            break;
                    }
                });

                /*
                * 选择枚举
                * */
                layui.form2.on('select(schoolIds)',function (res) {
                    if(res.value){
                        $.home.serchClass();
                        layui.form2.render('select','classId');
                        layui.form2.render('checkbox')
                    }
                });
                layui.form2.on('select(subjectId)',function (res) {
                    $.home.searchBook();
                    layui.form2.render('select','bookId');
                    layui.form2.render('checkbox')
                });
                layui.form2.on('select(subTypeArr)',function (res) {
                    $.home.searchBook();
                    layui.form2.render('select','bookId');
                    layui.form2.render('checkbox');
                });

                
                function type(subtype){
                    switch (subtype){
                        case 1:
                        case 3:
                        case 4:
                            return "正确题量";
                        case 2:
                        case 5:
                            return "失败次数";
                        default :
                            return '正确题量'
                    }
                }
                function topicOld(subtype) {
                    switch (subtype){
                        case 1:
                        case 3:
                        case 4:
                            return {field:'topicOld', width:110,sort: true,title:'总做题量',align:'right'};
                        case 2:
                        case 5:
                            return '';
                        default :
                            return {field:'topicOld', width:110,sort: true,title:'总做题量',align:'right'}
                    }
                }
            },
            ajaxRequest: function (url,type,data,sync,callback) {
                $.ajax({
                    url: url,
                    type:type,
                    data:data,
                    async: sync,
                    dataType: "json",
                    complete:function (XMLHttpRequest, textStatus) {
                        if(XMLHttpRequest.status===200){ 
                            XMLHttpRequest.responseJSON ? callback&&callback(XMLHttpRequest.responseJSON) : callback&&callback(JSON.parse(XMLHttpRequest.responseText));
                        }else{
                            $('.loading').hide();
                            layui.layer.msg(XMLHttpRequest.responseJSON.error,{icon:2})
                        }
                    }
                })
            }
        }
    }();
    $.home.init();
});